import React, {createRef, useState, useEffect} from "react";
import styled from 'styled-components';
import {Switch, Position, Popover, Menu, Icon, Tooltip, Button, Intent} from '@blueprintjs/core';
import {usePoetry} from "../ poetry-hooks";
import {Word} from "./Word";
import {IconNames} from "@blueprintjs/icons";
import {FullscreenManager} from "../fullscreen";
import {isFullScreen} from "react-request-fullscreen";
import {useInterval} from "../helpers/interval-hook";

const StyledLine = styled.div`
display: flex;
`;

const StyledLines = styled.div`
background-color: rgba(255, 250, 231, .9);
padding: 10px 20px;
`;

const StyledSwitchRightPanel = styled.div`
display: flex;
position: absolute;
right: 5px;
top: 5px;
justify-content: space-between;
.bp3-control {
  margin-right: 15px;
}
.bp3-popover-wrapper + .bp3-popover-wrapper {
  margin-left: 15px;
}
.bp3-popover-wrapper + .bp3-control {
  margin-left: 15px;
}
`;

const StyledSettingIconText = styled.span`
cursor: pointer;
`;

function Line(props) {
    return (<StyledLine>
        {props.line.map((v, index) => <><Word key={index} row={props.row} column={index} next={index!== props.line.length-1 ? props.line[index+1] : null} {...v}/>&nbsp;</>)}
    </StyledLine>)
}

function Lines(props) {
    return (<StyledLines>
        {props.lines.map((v, index) => <Line key={index} row={index} line={v}/>)}
    </StyledLines>)
}

export function PoetrySwitchPanel() {
    const {
        weakTip, toggleWeakTip,
        showTable, toggleTable,
        showPinyin, togglePinyin,
        showTone, toggleTone, trainFromError,
        toggleTrainFromError,
        trainFromErrorDisabled,
        errorRange, setErrorRange,
        counter, resetCounter,
        keyboard, toggleKeyboard
    } = usePoetry();
    const SettingMenu = <Menu>
        <Menu.Item active={errorRange === 1} text={`最近一次`} onClick={() => setErrorRange(1)}/>
        <Menu.Item active={errorRange === 3} text={`最近三次`} onClick={() => setErrorRange(3)}/>
        <Menu.Item text="重置计数器" onClick={resetCounter}/>
    </Menu>;
    const fullscreenRef = createRef();
    const [tipCounter, setTipCounter] = useState(0);
    const [paused, setPaused] = useState(false);

    const toggleMode = () => {
        reset();

        // 练习拼音时不是全屏就切换为全屏
        if (showPinyin) {
            if (!isFullScreen()) {
                fullscreenRef.current.fullScreen();
            }

            if (showTable) {
                toggleTable();
            }

            if (trainFromError) {
                toggleTrainFromError();
            }

            toggleWeakTip();
        }

        togglePinyin();
    };

    const counterGroup = <>
        <Tooltip content="已练习古诗数" position={Position.BOTTOM}>
            <span className="bp3-tag bp3-round bp3-intent-primary">{counter.trained}</span>
        </Tooltip>
        <Tooltip content="已强化古诗数" position={Position.BOTTOM}>
            <span className="bp3-tag bp3-round bp3-intent-success">{counter.stronger}</span>
        </Tooltip>
    </>;

    useEffect(() => {
        if (weakTip) {
            setPaused(false);
        }
    }, [weakTip]);

    useInterval(() => {
        if (tipCounter === 1) {
            reset();
        } else {
            setTipCounter(tipCounter - 1);
        }
    }, paused ? null : 1000);

    function toggle() {
        setPaused(!paused);
    }

    function reset() {
        setTipCounter(5);
        setPaused(true);
        if (weakTip) {
            toggleWeakTip();
        }
    }

    return <>
        <StyledSwitchRightPanel>
            {
                weakTip && <div style={{margin: '0 15px 0 0'}}>
                    <Tooltip content={`${paused ? '继续' : '暂停'} 倒计时`} position={Position.BOTTOM}>
                        <Button onClick={toggle} icon={paused ? IconNames.PLAY : IconNames.PAUSE} minimal={true}/>
                    </Tooltip>
                    <span className="bp3-tag bp3-round bp3-intent-primary"
                          style={{margin: '0 5px 0 0'}}>{tipCounter}秒后开始</span>
                    <Button onClick={reset} intent={Intent.PRIMARY}>现在开始</Button>
                </div>
            }
            {counterGroup}
            <Switch checked={showPinyin} label="切换模式" onChange={toggleMode}/>
            <Switch checked={showTone} label="声调" onChange={toggleTone} disabled={!showPinyin}/>
            <Switch checked={trainFromError} label="弱项强化" onChange={toggleTrainFromError}
                    disabled={trainFromErrorDisabled || !showPinyin}/>
            <Popover content={SettingMenu} position={Position.BOTTOM}>
                <Tooltip content={`弱项覆盖最近 ${errorRange} 次练习, 点击切换`} position={Position.BOTTOM}>
                    <StyledSettingIconText>
                        <Icon icon={IconNames.SETTINGS}/> ({errorRange})
                    </StyledSettingIconText>
                </Tooltip>
            </Popover>
            <Tooltip content={'切换键盘显示'} position={Position.BOTTOM}>
                <Icon icon={IconNames.KEY_COMMAND} onClick={toggleKeyboard} color={keyboard ? 'green' : 'gray'}/>
            </Tooltip>
            <FullscreenManager ref={fullscreenRef}/>
        </StyledSwitchRightPanel>
    </>
}

export function Text() {
    const {poetry} = usePoetry();

    return (
        <div>
            <form>
                <Lines lines={poetry.lines} key={poetry.title}/>
            </form>
        </div>
    );
}
